<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : AllowOriginMiddleware.php
 * Created on : 2020-7-25 10:04:07
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\http\middleware;

use haoteam\interfaces\MiddlewareInterface;
use app\Request;
use think\facade\Config;
use think\Response;

/**
 * 
 * Class AllowOriginMiddleware
 * Tiger <1192851302@qq.com> 2020-7-25 10:04:07
 */
class AllowOriginMiddleware implements MiddlewareInterface {

    /**
     * header头
     * @var array
     */
    protected $header = [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'Authori-zation, Authorization, Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
        'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
        'Access-Control-Max-Age' => 1728000
    ];

    /**
     * 允许跨域的域名
     * @var string
     */
    protected $cookieDomain;

    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next) {
        $this->cookieDomain = Config::get('cookie.domain', '');
        $header = $this->header;
        $origin = $request->header('origin');
        if ($origin && ('' != $this->cookieDomain && strpos($origin, $this->cookieDomain))) {
            $header['Access-Control-Allow-Origin'] = $origin;
        }
        if ($request->method(true) == 'OPTIONS') {
            $response = Response::create('ok')->code(200)->header($header);
        } else {
            $response = $next($request)->header($header);
        }
        $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
        return $response;
    }

}
